package com.lge.clock.alarmclock;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

/**
 * @author LGE Cappuccino
 */
public class WorldClockDB extends SQLiteOpenHelper {
	private String mDBName;
	private Context mContext;
	private static final String WORLDCITIESDB_PATH = "/data/data/com.lge.clock/databases/";
	private static final String WORLDCITIESDB_NAME = "worldcities.db";
	
	private static final int DTATBASE_VERSION = 1;
	
	public WorldClockDB(Context context, String name) {
	
		super(context, name, null, DTATBASE_VERSION);
		// TODO Auto-generated constructor stub
		mDBName = name;
		mContext = context;
		
	}
	
	public void createWorldCitiesDataBase() {
		boolean worldcitiesdbExist = checkWorldCitiesDataBase();
		if ( !worldcitiesdbExist) {
			try {
				copyWorldCitiesDataBase();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	private boolean checkWorldCitiesDataBase() {
		SQLiteDatabase checkDB = null;
		try {
			String myPath = WORLDCITIESDB_PATH + WORLDCITIESDB_NAME;
			checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
		} catch (SQLiteException e) {
			// database does't exist yet.
		} finally {
			if (checkDB != null) {
				checkDB.close();
			}
		}
		
		return checkDB != null ? true : false;
	}
	
	private void copyWorldCitiesDataBase() throws IOException {

		// Path to the just created empty db
		String outFileName = WORLDCITIESDB_PATH + WORLDCITIESDB_NAME;
		
		InputStream myInput = null;
		OutputStream myOutput = null;
		try {
			// Open your local db as the input stream
			myInput = mContext.getAssets().open("database/" + WORLDCITIESDB_NAME);
			
			// Open the empty db as the output stream
			myOutput = new FileOutputStream(outFileName);
			
			// transfer bytes from the inputfile to the outputfile
			byte[] buffer = new byte[1024];
			int length = myInput.read(buffer);
			while ( length > 0 ) {
				myOutput.write(buffer, 0, length);
				length = myInput.read(buffer);
			}
			
			Log.i("WorldClockDB", "copyWorldCitiesDataBase close");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (myInput != null) {
				try {
					myInput.close();
				} catch (Exception e) {}
			}
			
			// Close the streams
			if ( myOutput != null ) {
				try{
					myOutput.flush();
				}catch(Exception e){}
				
				try{
					myOutput.close();
				}catch(Exception e){}
			}
		}
	}
	
	@Override
	public void onCreate(SQLiteDatabase db) {
		// TODO Auto-generated method stub
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		// TODO Auto-generated method stub
	}

	@Override
	public synchronized void close() {
		// TODO Auto-generated method stub
	}
}
